#include "stdafx.h"
#include "CLRDB.h"

namespace CLRDB
{
	MySQLDBManager^ MySQLDBManager::GetInstance()
	{
		if( g_Instance == nullptr )
		{
			g_Instance = gcnew MySQLDBManager();
		}

		return g_Instance;
	}

	MySQLDBManager::MySQLDBManager(void)
	{
		m_ConnectionString = nullptr;
		m_Connection = nullptr;
	}

	DataSet^ MySQLDBManager::GetDataXMLDataSet()
	{
		return nullptr;
	}

	bool MySQLDBManager::Initialize( String^ connectionString )
	{
		m_ConnectionString = connectionString;

		try
		{
			m_Connection = gcnew MySql::Data::MySqlClient::MySqlConnection( m_ConnectionString );
			m_Connection->Open();
		}
		catch( MySqlException^ ex )
		{
			Debug::WriteLine( "MySQL initialize failed!! desc:{0}", ex->Message );
			return false;
		}

		return true;
	}

	bool MySQLDBManager::TruncateTable( System::String^ table_name )
	{
		if( m_Connection == nullptr )
			return false;

		try
		{
			MySqlClient::MySqlCommand^ command = m_Connection->CreateCommand();
			command->CommandText = "truncate table " + table_name;
			command->ExecuteNonQuery();
		}
		catch( MySqlException^ ex)
		{
			Debug::WriteLine( "truncate table {0} failed!! desc:{1}", table_name, ex->Message );
			return false;
		}
		return true;
	}

	bool MySQLDBManager::GetTableColumns( System::String^ table_name, ArrayList^ listColumns )
	{
		if( m_Connection == nullptr )
			return false;

		MySqlDataReader^ reader = nullptr;

		try
		{
			MySqlClient::MySqlCommand^ command = m_Connection->CreateCommand();
			command->CommandText = "show columns from " + table_name;
			reader = command->ExecuteReader();
			while( reader->Read() == true )
			{
				auto column_name = reader->GetValue(0);
				listColumns->Add( column_name );
			}
		}
		catch( MySqlException^ ex)
		{
			Debug::WriteLine( "truncate table {0} failed!! desc:{1}", table_name, ex->Message );
			return false;
		}
		finally
		{
			if( reader != nullptr )
				reader->Close();
		}
		return true;
	}

	bool MySQLDBManager::InsertData( String^ tableName, DataSet^ dataSet, String^ error )
	{
		String^ storedProcedureName = "sp_Insert" + tableName;

		MySqlCommand^ command = m_Connection->CreateCommand();
		command->CommandType = CommandType::StoredProcedure;
		command->CommandText = storedProcedureName;

		DataTable^ table = dataSet->Tables[0];
		for( int i = 0 ; i < table->Rows->Count ; ++i )
		{
			command->Parameters->Clear();

			DataRow^ row = table->Rows[i];
			for( int j = 0 ; j < row->ItemArray->Length ; ++j )
			{
				DataColumn^ col = table->Columns[j];
				auto value = row->ItemArray[j];

				MySqlParameter^ parameter = gcnew MySqlParameter(col->ColumnName, value);
				command->Parameters->Add(parameter);
			}
			command->ExecuteNonQuery();
		}
		return true;
	}
}
